package com.ledim.datastatistics;

import android.content.Context;
import android.text.TextUtils;
import com.ledim.app.LeDimApplication;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.letv.android.client.LetvSDK;
import com.letv.business.flow.album.model.AlbumPlayInfo;
import com.letv.core.config.LetvConfig;
import com.letv.core.utils.LetvSDKUtils;
import com.letv.tracker.msg.bean.Version;
import com.letv.tracker2.agnes.Agnes;
import com.letv.tracker2.agnes.App;
import com.letv.tracker2.agnes.Event;
import com.letv.tracker2.agnes.MusicPlay;
import com.letv.tracker2.agnes.VideoPlay;
import com.letv.tracker2.agnes.Widget;
import com.letv.tracker2.enums.Area;
import com.letv.tracker2.enums.EventType;
import com.letv.tracker2.enums.HwType;
import com.letv.tracker2.enums.Key;
import com.letv.tracker2.enums.LeUIApp;
import com.letv.tracker2.enums.PlayStart;
import com.letv.tracker2.enums.PlayType;
import java.util.Map;
import java.util.Set;

/**
 * Created by ccx on 16/5/30.
 * 乐视大数据通用版上报工具类
 */
public class LeDimAnalysisUtils {

    public static App leDimapp = null;
    private static final String APP_NAME = "LeDimension_android";
    private static final String AU_ID = "auid";
    public static final String CHOICE_PAGE_CODE = "001";
    public static final String ROOM_PAGE_CODE = "002";
    public static final String MINE_PAGE_CODE = "033";
    public static final String ROOM_ADD_CODE = "023";
    public static final String ROOM_SEARCH_CODE = "022";
    public static final String ALBUM_SEARCH_CODE = "042";

    private static App getLeDimApp() {
        Agnes agnes = Agnes.getInstance();
        if (leDimapp == null) {
            if (LeUIApp.isExsited(APP_NAME)) {
                leDimapp = agnes.getApp(LeUIApp.valueOf(APP_NAME));
            } else {
                leDimapp = agnes.getApp(APP_NAME);
            }
        }
        Version version = leDimapp.getVersion();
        version.setVersion(LeDimApplication.getInstance().getAppVersionName());
        return leDimapp;
    }

    /**
     * @param widgetId
     * @param type
     * @param pampers
     * @return 通过信息生成Event事件
     *
     * @throws Exception
     */
    private static Event generateEvent(String widgetId, Object type, Map<String, String> pampers)
            throws Exception {
        Event event;
        if (!TextUtils.isEmpty(widgetId)) {
            Widget widget = getLeDimApp().createWidget(widgetId);
            if (type instanceof EventType) {
                event = widget.createEvent((EventType) type);
            } else if (type instanceof String) {
                event = widget.createEvent((String) type);
            } else {
                throw new Exception("not support Event Type");
            }

        } else {
            if (type instanceof EventType) {
                event = getLeDimApp().createEvent((EventType) type);
            } else if (type instanceof String) {
                event = getLeDimApp().createEvent((String) type);
            } else {
                throw new Exception("not support Event Type");
            }
        }
        if (pampers != null && !pampers.isEmpty()) {
            Set<Map.Entry<String, String>> sets = pampers.entrySet();
            for (Map.Entry<String, String> entry : sets) {
                Key proKey = null;
                try {
                    proKey = Key.valueOf(entry.getKey());
                } catch (Exception e) {

                }
                if (proKey != null) {
                    event.addProp(proKey, entry.getValue());
                } else {
                    event.addProp(entry.getKey(), entry.getValue());
                }
            }

        }
        event.addProp(Key.auid, getDeviceId());
        if (LedimSpUtils.isLogin()) {
            event.addProp("uid", LedimSpUtils.getUid());
        } else {
            //这sdk逻辑需求也是醉了
            event.addProp("uid", "-");
        }

        return event;
    }

    public static String getDeviceId() {
        String deviceId = LedimSpUtils.getDeviceId();
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = AnalysisDataUtils.generateDeviceId(LeDimApplication.getInstance()
                                                                          .getApplicationContext());
            LedimSpUtils.setDeviceId(deviceId);
        }
        return deviceId;
    }

    /**
     * @param context
     *         初始化数据上报实例
     */
    public static void initAnalysis(Context context) {
        // 通用手机，大陆
        Agnes.getInstance(HwType.PHONE_COMMON, Area.CN).setContext(context);
        if (LedimSpUtils.getDebugMark()) {
            Agnes.getInstance().getConfig().enableLog();
        }
    }

    /**
     * 上传手机信息
     */
    public static void reportEvenvironment() {
        Agnes.getInstance().reportEnv();
    }

    /**
     * @param widgetId
     * @param type
     * @param pampers
     *         上传事件
     */
    public static void reportEvent(String widgetId, Object type, Map<String, String> pampers) {
        try {
            Event event = generateEvent(widgetId, type, pampers);
            Agnes.getInstance().report(event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param eventType
     *         不会含有widget的事件以及事件属性为空的Event上传
     */
    public static void reportEvent(Object eventType) {
        reportEvent(null, eventType, null);
    }

    /**
     * @param eventType
     *         不会含有widget的事件上传(但是有Event属性map)
     */
    public static void reportEvent(Object eventType, Map<String, String> pampers) {
        reportEvent(null, eventType, pampers);
    }

    /**
     * @param widgetId
     * @param eventType
     *         含有widget的事件上传(但是没有Event属性map)
     */
    public static void reportEvent(String widgetId, EventType eventType) {
        reportEvent(widgetId, eventType, null);
    }

    public static String getAnalysisVersion() {
        return Agnes.getInstance().getVersion();
    }

    public static void reprotMusicPlayEvent(Map<String, String> params,
                                            Map<String, String> actions) {
        MusicPlay musicPlay = getLeDimApp().createMusicPlay();
    }

    //public static void reprotVideoPlayEvent(Map<String, String> params,
    //                                        Map<String, String> actions) {
    //    VideoPlay vedioPlay = getLeDimApp().createVideoPlay();
    //
    //}

    /**
     * @return
     * 初始化videoPlay对象
     */
    public static VideoPlay generatePlayEvent() {
        return getLeDimApp().createVideoPlay();
    }

    /**
     * @param channel_id
     *         渠道ID
     * @param album_id
     *         专辑ID
     * @param subject_id
     *         专题ID
     * @param url
     * @param stream
     * @param length
     * @param ipt
     *         * 0 ：点播；
     *         1：连播；
     *         2：切换码流
     * @param videoPlayInstance
     *         为null重新创建
     * @return 生成VideoPlay，并设置必须上传数据
     */
    public static void setVidoPlayCommonPro(long channel_id, long album_id, long subject_id,
                                            String url, String stream, long length, int ipt,
                                            VideoPlay videoPlayInstance) {
        if (LedimSpUtils.isLogin()) {
            videoPlayInstance.addProp("uid", LedimSpUtils.getUid());
        } else {
            //这sdk逻辑需求也是醉了
            videoPlayInstance.addProp("uid", "-");
        }
        videoPlayInstance.setType(PlayType.OnDemand);
        videoPlayInstance.setNetworkModel(AnalysisDataUtils.getNetworkType(LeDimApplication.getInstance()));
        videoPlayInstance.setProductCode(LetvConfig.getPcode(LeDimApplication.getInstance()
                                                                             .getApplicationContext()));
        videoPlayInstance.setAuid(getDeviceId());
        videoPlayInstance.setChannelId(String.valueOf(channel_id));
        videoPlayInstance.setAlbumId(String.valueOf(album_id));
        videoPlayInstance.setSubjectId(String.valueOf(subject_id));
        videoPlayInstance.setUrl(url);
        videoPlayInstance.setBitStream(stream);
        videoPlayInstance.setPush(String.valueOf(LetvSDK.getPushType()));
        //TODO 时长应该是long类型
        if (length != 0) {
            videoPlayInstance.setVideoLength((int) length);
        }
        videoPlayInstance.setInvokePlayType(String.valueOf(ipt));
    }

    /**
     * @param videoPlay
     *         上传视频事件
     */
    public static void reportPlayEvent(VideoPlay videoPlay) {
        Agnes.getInstance().report(videoPlay);
    }

    /**
     * @param videoPlay
     * @param playInfo
     *         上传开始播放事件
     */
    public static void reportStartPlayEvent(VideoPlay videoPlay, AlbumPlayInfo playInfo) {
        //验证播放记录和是否缓存时长
        videoPlay.addProp("type3", "0");
        // 请求接口时长，获取播放记录之后开始到接口返回的时间
        videoPlay.addProp("type7", AnalysisDataUtils.timeToString(playInfo.albumPayConsumeTime));
        // 获取广告拼接时长=>从调用地址接口到接口数据返回的时间(没广告时或者直播时为0)
        videoPlay.addProp("type8", AnalysisDataUtils.timeToString(playInfo.mAdsJoinTime));
        // 获取正式播放地址时长=>从请求调用真实播放开始到接口数据返回的时间（android）
        videoPlay.addProp("type9", AnalysisDataUtils.timeToString(playInfo.getRealUrlConsumeTime));
        // 汇总时长=>汇总时长是从点击视频海报到第一帧画面出现的时长（起播时长）
        // type10>type7+type9+type8(有广告时考虑)+type11+type13
        videoPlay.addProp("type10", AnalysisDataUtils.timeToString(playInfo.mTotalConsumeTime));
        //// 广告接口请求时长=>从请求广告接口到接口返回解析数据完成时间
        //videoPlay.addProp("type12", AnalysisDataUtils.timeToString(playInfo.mAdsRequestTime));
        // 广告总时长
        videoPlay.addProp("type12", AnalysisDataUtils.timeToString(playInfo.mAdsToalTime));
        // 视频加载时长=>拿到url播放地址到第一帧画面出现的时长(有广告是广告的加载时长，无广告是正片的加载时长)
        String loadingConsumeTimeTmp = AnalysisDataUtils.timeToString(
                playInfo.mAdCount > 0 ? playInfo.mAdsLoadConsumeTime
                                      : playInfo.mVideoLoadConsumeTime);
        videoPlay.addProp("type13", loadingConsumeTimeTmp);
        // 进入播放页加载时长，正片加载时长=>拿到正片最终播放地址到出现正片第一帧画面的时长（Android端有）
        videoPlay.addProp("type14", AnalysisDataUtils.timeToString(playInfo.mVideoLoadConsumeTime));
        //type7到type8的时长 这个不应该客户端上传
        videoPlay.addProp("type15", AnalysisDataUtils.timeToString(
                playInfo.albumPayConsumeTime - playInfo.mAdsJoinTime));
        // 已经上传
        videoPlay.addProp("playerType", "0");//非系统播放器

        try {
            videoPlay.addProp("videoSend", playInfo.mVideoSend.split("vsend=")[1]);
            videoPlay.addProp("videoFormat", playInfo.mVformat.split("vformat=")[1]);
        } catch (Exception e) {
            LogUtil.e(e.getMessage());
        }
        videoPlay.startPlay(PlayStart.Auto);
        Agnes.getInstance().report(videoPlay);
    }

    /**
     * @param videoPlay
     *         上传视频初始化事件
     */
    public static void reportInitPlayEvent(VideoPlay videoPlay) {
        videoPlay.setCdeAppId(LetvConfig.getAppId());
        videoPlay.setCdeVersion(LetvSDKUtils.getCdeHelper(LeDimApplication.getInstance())
                                            .getServiceVersion());
        Agnes.getInstance().report(videoPlay);
    }
}
